package com.th.therp.controller;

import com.th.therp.exception.BaseException;
import com.th.therp.pojo.dto.MaterialStatusDto;
import com.th.therp.pojo.dto.page.MaterialPageQueryDTO;
import com.th.therp.pojo.emtity.Material;
import com.th.therp.pojo.result.PageResult;
import com.th.therp.pojo.result.Result;
import com.th.therp.service.MaterialService;
import jakarta.validation.Valid;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 商品请求控制器
 */
@Log4j2
@RestController
@RequestMapping("/material")
public class MaterialController {

    @Autowired
    private MaterialService materialService;

    //新增商品
    @PostMapping()
    @ResponseBody
    public Result add(@Valid @RequestBody Material material, BindingResult bindingResult) {
        log.info("新增商品:{}",material);
        if (bindingResult.hasErrors()) {
            throw new BaseException("格式不正确");
        }
        materialService.add(material);
        return Result.success();
    }

    //商品分页查询
    @GetMapping("/page")
    @ResponseBody
    public Result<PageResult> page(MaterialPageQueryDTO materialPageQueryDTO) {
        log.info("商品分页查询:{}",materialPageQueryDTO);
        PageResult pageResult = materialService.page(materialPageQueryDTO);
        return Result.success(pageResult);
    }

    //修改商品
    @PutMapping()
    @ResponseBody
    public Result update(@Valid @RequestBody Material material, BindingResult bindingResult) {
        log.info("修改商品:{}",material);
        if (bindingResult.hasErrors()) {
            throw new BaseException("格式不正确");
        }
        materialService.update(material);
        return Result.success();
    }

    //修改商品状态
    @PutMapping("/status")
    @ResponseBody
    public Result updateStatus(@RequestBody MaterialStatusDto materialStatusDto) {
        log.info("修改商品状态: {}", materialStatusDto);
        Integer status = materialStatusDto.getStatus();
        // 将逗号分隔的字符串转化为 List<Integer>
        List<Integer> idList = Arrays.stream(materialStatusDto.getIds().split(","))
                .map(Integer::parseInt)
                .toList();
        materialService.updateStatus(idList,status);
        return Result.success();
    }

    //删除商品
    @DeleteMapping()
    @ResponseBody
    public Result delete(@RequestParam List<Integer> ids) {
        log.info("删除商品:{}",ids);
        materialService.delete(ids);
        return Result.success();
    }

    //根据供应商ID查询商品
    @GetMapping("/findByVendorId")
    @ResponseBody
    public Result<List<Material>> findByVendorId(@RequestParam Long vendorId) {
        log.info("根据供应商id查询商品:{}",vendorId);
        List<Material> materialList = materialService.findByVendorId(vendorId);
        return Result.success(materialList);
    }
}